const rootPath = import.meta.env.VITE_APP_BASE_API;
import DoubleToken from "@/api/modules/user/receive/DoubleToken";
import $store from "@/plugins/shop";

const getDoubleToken = function (): DoubleToken {
  const doubleToken: DoubleToken = $store.user.getDoubleToken();
  if (doubleToken == null) {
    throw null;
  }
  return doubleToken ?? new DoubleToken();
};
const request = function (obj: {
  url: string;
  method:
    | "OPTIONS"
    | "GET"
    | "HEAD"
    | "POST"
    | "PUT"
    | "DELETE"
    | "TRACE"
    | "CONNECT";
  data?: object;
  query?: object;
  header?: object;
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
}): Promise<any> {
  const doubleToken = getDoubleToken();
  return new Promise((resolve, reject) => {
    // 如果当前是get请求，有query参数，那将query对象赋值于data,这是由uniapp 的uni.request决定的，没有提供query，而如果是get请求data就是query
    // 兼容代码
    if (/get/i.test(obj.method)) {
      if (obj.data === null) {
        obj.data = obj.query;
      }
    }
    // 如果没有token就不带认证信息请求
    if (doubleToken != null && doubleToken.accessToken != null) {
      if (obj.header == null) {
        obj.header = {};
      }
      obj.header = {
        Authorization: `${doubleToken.tokenType} ${doubleToken.accessToken}`,
        ...obj.header,
      };
    }
    uni.request({
      url: rootPath + obj.url, //仅为示例，并非真实接口地址。
      method: obj.method,
      data: obj.data ?? {},
      header: obj.header ?? {},
      success: (res) => {
        resolve(res.data);
      },
      fail: (error) => {
        reject(error);
      },
    });
  });
};

// 对外暴露
export default request;
